package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC1818 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        int factor = 1000000007;

        public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {
            TreeSet<Integer> set = new TreeSet<>();
            for (int num : nums1) {
                set.add(num);
            }

            int maxReduceDiff = Integer.MIN_VALUE, finalDiff = 0;
            for (int i = 0; i < nums1.length; i++) {
                int ceiling = (set.ceiling(nums2[i]) == null) ? nums1[i] : set.ceiling(nums2[i]);
                int floor = (set.floor(nums2[i]) == null) ? nums1[i] : set.floor(nums2[i]);

                int curCanDoneMinDiff = Math.min(Math.abs(ceiling - nums2[i]), Math.abs(floor - nums2[i]));
                maxReduceDiff = Math.max(maxReduceDiff, Math.abs(nums1[i] - nums2[i]) - curCanDoneMinDiff);
                finalDiff = (finalDiff + Math.abs(nums1[i] - nums2[i])) % factor;
            }
            System.out.println("finalDiff - maxReduceDiff" + finalDiff + ", " + maxReduceDiff);
            return (finalDiff - maxReduceDiff) % factor;
        }
    }

    public void run() {
        Solution solution = new Solution();
//        nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
        int[] arr1 = InputUtil.toIntegerArray("[38,48,73,55,25,47,45,62,15,34,51,20,76,78,38,91,69,69,73,38,74,75,86,63,73,12,100,59,29,28,94,43,100,2,53,31,73,82,70,94,2,38,50,67,8,40,88,87,62,90,86,33,86,26,84,52,63,80,56,56,56,47,12,50,12,59,52,7,40,16,53,61,76,22,87,75,14,63,96,56,65,16,70,83,51,44,13,14,80,28,82,2,5,57,77,64,58,85,33,24]");
        int[] arr2 = InputUtil.toIntegerArray("[90,62,8,56,33,22,9,58,29,88,10,66,48,79,44,50,71,2,3,100,88,16,24,28,50,41,65,59,83,79,80,91,1,62,13,37,86,53,43,49,17,82,27,17,10,89,40,82,41,2,48,98,16,43,62,33,72,35,10,24,80,29,49,5,14,38,30,48,93,86,62,23,17,39,40,96,10,75,6,38,1,5,54,91,29,36,62,73,51,92,89,88,74,91,87,34,49,56,33,67]");
//        int[] arr1 = InputUtil.toIntegerArray("[150,100]");
//        int[] arr2 = InputUtil.toIntegerArray("[90,10]");

        System.out.println(solution.minAbsoluteSumDiff(arr1, arr2));
    }

    public static void main(String[] args) throws Exception {
        LC1818 an = new LC1818();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
